#include <iostream>
#include <memory>
#include <string>
#include <functional>
#include "ThreadPoll.hpp"
#include "Socket.hpp"
#include "Log.hpp"

namespace TcpEchoServerModule
{
    using Handler = std::function<void(uint16_t, std::string)>;
    using namespace SocketModule;
    using namespace LogModule;
    using namespace ThreadPollModule;

    const static uint16_t defaultport = 8888;
    const static std::string defaultip = "0.0.0.0";

    class TcpEchoServer
    {

    public:
        TcpEchoServer(uint16_t port = defaultport, std::string ip = defaultip)
            : _socket(std::make_shared<TcpSocket>()), _port(port), _ip(ip)
        {
            _socket->CreateTcpSocket(_port, _ip);
        }

        void Start()
        {
            while (true)
            {
                std::string ip;
                uint16_t port;
                std::shared_ptr<Socket> sock = _socket->AcceptConnect(&port, &ip);
                using func_t = std::function<void()>;
                func_t in = std::bind(&TcpEchoServer::Service, this, port, ip, sock);
                // 1. 取单例
                ThreadPoll *tp = ThreadPoll::GetInstance();

                // 2. 启动线程池
                tp->Start();
                tp->Enqueue(in);
            }
        }

        void Service(uint16_t port, std::string ip, std::shared_ptr<Socket> sock)
        {
            while (true)
            {
                LOG(LogLevel::DEBUG) << sock->GetSocket();
                std::string msg;
                sock->ReadMessage(&msg);
                // 设置退出功能
                // to do
                //
                std::string body = "<h1>hello,world</h1>";
                std::string resp = "HTTP/1.1 200 OK\n"
                                   "Content-Type: text/html\n"
                                   "Content-Length: " +
                                   std::to_string(body.size()) + "\n"
                                                                 "\n" +
                                   body;
                LOG(LogLevel::INFO) << "server receive message form client : " << msg;
                sock->WriteMessage(&resp);
                LOG(LogLevel::INFO) << "server send message to client : " << resp;
            }
        }

    private:
        std::shared_ptr<Socket> _socket;
        uint16_t _port;
        std::string _ip;
        Handler _handler; // 进程池的回调
    };
}